package com.example.zhang.downloadapk;

import android.app.DownloadManager;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.example.zhang.downloadapk.downloadapk.Constants;
import com.example.zhang.downloadapk.downloadapk.DownLoadRunnable;
import com.example.zhang.downloadapk.downloadapk.DownloadDialog;
import com.example.zhang.downloadapk.downloadapk.Utils;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Utils.init(MainActivity.this);
    }


    public void downLoad(String url, int state) {
        if (state == Constants.FORCIBLEY) {
            showDialog();
        }
        //最好是用单线程池，或者intentService取代
        new Thread(new DownLoadRunnable(url, state, handler)).start();
    }

    private DownloadDialog downloadDialog;

    /**
     * 显示下载进度的弹窗
     */
    public void showDialog() {
        if (downloadDialog == null) {
            downloadDialog = new DownloadDialog(MainActivity.this);
        }
        if (!downloadDialog.isShowing()) {
            downloadDialog.show();
        }
    }

    public void cancleDialog() {
        if (downloadDialog != null && downloadDialog.isShowing()) {
            downloadDialog.dismiss();
        }
    }

    //handler更新ui
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case DownloadManager.STATUS_SUCCESSFUL:
                    downloadDialog.setProgress(100);
                    cancleDialog();
                    break;
                case DownloadManager.STATUS_RUNNING:
                    downloadDialog.setProgress((int) msg.obj);
                    break;
                case DownloadManager.STATUS_FAILED:
                    cancleDialog();
                    break;
                case DownloadManager.STATUS_PENDING:
                    showDialog();
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onDestroy() {
        cancleDialog();
        super.onDestroy();
    }
}
